<template>
	<view class="TUI-message-input-main" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
		@touchend="handleTouchEnd">
		<text class="text">{{ text }}</text>
		<!-- <view class="record-modal" v-if="isRecording">
			<view class="wrapper">
				<view class="modal-loading"></view>
			</view>
			<view class="modal-title">
                <text class="text">{{ title }}</text>
            </view>
		</view> -->
	</view>
</template>

<script lang="ts">
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import permision from "@/utils/permission.ts"
	import {
		defineComponent,
		watchEffect,
		reactive,
		toRefs,
		onMounted
	} from 'vue';
	// #ifndef H5
	// #endif
	const AudioMessage = defineComponent({
		props: {
			show: {
				type: Boolean,
				default: () => {
					return false;
				}
			},
		},
		setup(props: any, ctx: any) {


            const recorderManager = uni.getRecorderManager();

            const systemInfo = systemInfoStore();

			const data = reactive({
				popupToggle: false,
				isRecording: false,
				canSend: true,
				text: '按住说话',
				recorderManager: null,
				title: ' ',
				recordTime: 0,
				recordTimer: null,
                screenY:0,
			});

			onMounted(() => {

                recorderManager.onError(err=>{
                    console.log('eeeeeeeeeee')
                    console.log('eeeeeeeeeee')
                    console.log('eeeeeeeeeee')
                    console.log(err)
                })

				// 加载声音录制管理器
				recorderManager.onStop(res => {

                    console.log('sssssssssss')
                    console.log('sssssssssss')
                    console.log('sssssssssss')
                    console.log('sssssssssss')

					clearInterval(data.recordTimer);
					// 兼容 uniapp 打包app，duration 和 fileSize 需要用户自己补充
					// 文件大小 ＝ (音频码率) x 时间长度(单位:秒) / 8
					let msg = {
						duration: res.duration ? res.duration : data.recordTime * 1000,
						tempFilePath: res.tempFilePath,
						fileSize: res.fileSize ? res.fileSize : ((48 * data.recordTime) / 8) *
							1024
					};
					uni.hideLoading();
					// 兼容 uniapp 语音消息没有duration
					if (data.canSend) {
						if (msg.duration < 1000) {
							uni.showToast({
								title: '录音时间太短',
								icon: 'none'
							});
						} else {
							// res.tempFilePath 存储录音文件的临时路径
							uni.$TUIKit.TUIChatServer.sendAudioMessage(msg)
						}

                        uni.$emit('updateAudioStatu','');


					}else{

                        uni.$emit('updateAudioStatu','已取消');
                        setTimeout(()=>{
                            uni.$emit('updateAudioStatu','');
                        },600)

                    }

                    data.popupToggle = false;
                        data.isRecording = false;
                        data.canSend = true;
                        data.title = '';
                        data.text = '按住说话'
				});
			});


			const handleLongPress = async () => {
                console.log('handleLongPress')
                console.log('handleLongPress')
                console.log(systemInfo.platform)
				data.popupToggle = true;


                const option = {
						duration: 60000,
						// 录音的时长，单位 ms，最大值 600000（10 分钟）
                        sampleRate: 44100,
						// 采样率
						numberOfChannels: 1,
						// 录音通道数
                        encodeBitRate: 192000,
						// 编码码率
						format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
					}

                    if(systemInfo.platform==='android'){
                        option.format='mp3';
                    }

					recorderManager.start(option);
					data.title = '正在录音',
                    uni.$emit('updateAudioStatu','正在录音');
					data.isRecording = true,
					data.recordTime = 0
				data.recordTimer = setInterval(() => {
					data.recordTime++;
				}, 1000);
			};

			// 录音时的手势上划移动距离对应文案变化
			const handleTouchMove = (e: any) => {

                // console.log('handleTouchMove');
                // console.log(e);
				if (data.isRecording) {
					if (data.screenY-e.changedTouches[e.changedTouches.length - 1].screenY >
						100) {
						data.text = '抬起停止';
						data.title = '松开手指,取消发送';
                        uni.$emit('updateAudioStatu','松开手指,取消发送');
						data.canSend = false;
					} else if (data.screenY-e.changedTouches[e.changedTouches.length - 1].screenY > 20) {
						data.text = '抬起停止';
						data.title = '上划可取消';
                        uni.$emit('updateAudioStatu','上划可取消');
						data.canSend = true;
					} else {
						data.text = '抬起停止';
						data.title = '正在录音';
                        uni.$emit('updateAudioStatu','正在录音');
						data.canSend = true;
					}
				}
			};

            const handleTouchStart = async (e)=>{
                // console.log('handleTouchStart')
                // console.log(e)

                if(uni.platform === 'ios'){



                    
                    const couldRecord = permision.judgeIosPermission('record')
                    if(!couldRecord){


                        const fisrtRecord = uni.getStorageSync('fisrtRecord');


                        if(!fisrtRecord){
                            const option = {
                                duration: 60000,
                                // 录音的时长，单位 ms，最大值 600000（10 分钟）
                                sampleRate: 44100,
                                // 采样率
                                numberOfChannels: 1,
                                // 录音通道数
                                encodeBitRate: 192000,
                                // 编码码率
                                format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
                            }

                            recorderManager.start(option);

                             uni.setStorageSync('fisrtRecord',true);

                            return;

                        }


                        uni.showModal({
                            title: `无法使用麦克风`,
                            content: "当前无麦克风使用权限，建议前往系统设置，允许应用访问[麦克风]",
                            showCancel: true,
                            confirmText: "前往系统设置",
                            cancelText: "取消",
                            async success({ confirm, cancel }) {
                                if (confirm) {
                                    permision.gotoAppPermissionSetting();
                                }
                            },
                        });


                        return;
                    }
                }



                if(systemInfo.platform==='android'){

                    const fisrtRecord = uni.getStorageSync('fisrtRecord');


                    const res = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO').catch(err=>{
                    });


                    uni.setStorageSync('fisrtRecord',true);

                    if(res!==1){
                        uni.showModal({
                            title: `无法使用麦克风`,
                            content: "当前无麦克风使用权限，建议前往权限设置，允许应用访问[麦克风]",
                            showCancel: true,
                            confirmText: "前往系统设置",
                            cancelText: "取消",
                            async success({ confirm, cancel }) {
                                if (confirm) {
                                    permision.gotoAppPermissionSetting();
                                }
                            },
                        });

                        return;
                    }

                    if(!fisrtRecord){
                        return;
                    }
                    
                }

                handleLongPress();
                data.screenY = e.changedTouches[0].screenY;

            }

			// 手指离开页面滑动
			const handleTouchEnd = () => {

                console.log('handleTouchEnd')
                console.log('handleTouchEnd')
                console.log('handleTouchEnd')
                console.log(recorderManager)
                console.log(recorderManager.stop)
                recorderManager.stop();
                data.screenY = 0;
				data.isRecording = false;
				data.popupToggle = false;
				data.text = '按住说话';
				uni.hideLoading();
			};
			// 发送需要上传的消息：视频
			const sendUploadMessage = (e: any) => {
				Video.TUIServer.sendVideoMessage(e.target);
			};

			return {
				...toRefs(data),
				sendUploadMessage,
				handleLongPress,
                handleTouchStart,
				handleTouchEnd,
				handleTouchMove,
			};
		},
	});
	export default AudioMessage;
</script>

<style lang="scss" scoped>
	.audio-contain {
		display: flex;
		justify-content: center;
		font-size: 32rpx;
		font-family: PingFangSC-Regular;
	}

	.TUI-message-input-main {
		background-color: #1DC691;
		flex: 1;
		height: 80rpx;
		border-radius: 5rpx;
		display: flex;
        flex-direction: row;
		align-items: center;
        justify-content: center;
        .text{
            color:#fff;
        }
	}

	.record-modal {
		height: 300rpx;
		width: 450rpx;
		background-color: #000;
		opacity: 0.8;
		position: fixed;
		top: 670rpx;
		z-index: 9999;
		left: 150rpx;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
	}

	.record-modal .wrapper {
		display: flex;
		height: 200rpx;
		box-sizing: border-box;
		padding: 75rpx;
	}

	.record-modal .wrapper .modal-loading {
		opacity: 1;
		width: 40rpx;
		height: 16rpx;
		border-radius: 4rpx;
		background-color: #006fff;
		animation: loading 2s cubic-bezier(0.17, 0.37, 0.43, 0.67) infinite;
	}

	@keyframes loading {
		0% {
			transform: translate(0, 0)
		}

		50% {
			transform: translate(30vw, 0);
			background-color: #f5634a;
			width: 40px;
		}

		100% {
			transform: translate(0, 0);
		}
	}

	.modal-title {
		text-align: center;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        .text{
            color:#fff;
        }
	}
</style>
